package com.yfp.operation.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Description: RedisTemplate 分布式锁+等待队列
 *
 * @CreateDate: 2024/7/30 11:43
 * @UpdateUser:
 * @UpdateDate: 2024/7/30 11:43
 * @UpdateRemark: 暂无修改
 * @Version: 1.0
 */
@Slf4j
public class RedisDistributedLock {

    private RedisTemplate redisTemplate;
    private String lockKey;
    private String lockValue;
    private long expireTime;

    public RedisDistributedLock(RedisTemplate redisTemplate, String lockKey, long expireTime) {
        this.redisTemplate = redisTemplate;
        this.lockKey = lockKey;
        this.lockValue = UUID.randomUUID().toString();
        this.expireTime = expireTime;
    }

    /**
     * 加锁
     * @return
     */
    public boolean tryLock() {
        Boolean result = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, expireTime, TimeUnit.SECONDS);
        return result;
    }

    /**
     * 加锁+队列
     * @throws InterruptedException
     */
    public void lock() throws InterruptedException {
        while (!tryLock()) {
            // 等待一段时间再尝试获取锁
            Thread.sleep(100);
            log.info("等待一段时间再尝试获取锁");
        }
    }

    /**
     * 释放锁
     */
    public void unlock() {
        redisTemplate.delete(lockKey);
        log.info("释放锁" );
    }
}